package com.cloudcc.mobile.view.activity;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreHandler;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreListViewContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicDefaultHeader;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.header.MaterialHeader;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.im.adapter.MemberAdapter;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.NameComParatorMember;
import com.cloudcc.mobile.view.fragment.MenuRightFragment;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.adapter.NSystemAdapter;
import com.mypage.bean.CnumberBean;
import com.mypage.utils.SaveTemporaryData;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class DraftBoxGetDataActivity extends com.cloudcc.mobile.view.base.BaseActivity implements PtrHandler,LoadMoreHandler {

    @Bind(R.id.backcowor)
    ImageView backcowor;
    @Bind(R.id.bar_title_text)
    TextView barTitleText;
    @Bind(R.id.gzlist)
    ListView gzlist;
    @Bind(R.id.zanwushuju)
    TextView zanwushuju;
    @Bind(R.id.zanwushujufl)
    FrameLayout zanwushujufl;
    @Bind(R.id.load_more_list_view_ptr_frame)
    public PtrFrameLayout mRefreshLayout;
    @Bind(R.id.ivRightMenu)
    ImageView ivRightMenu;
    //    @Bind(R.id.load_more_list_view_container)
//    public LoadMoreListViewContainer mLoadMoreLayout;
    private String isguanzhu_x;
    private String gzuid;
    private List<CnumberBean.NumberData> guanzhudatea;
    private NameComParatorMember sortName;
    public NSystemAdapter adapter;
//    @Bind(R.id.load_more_list_view_container)
//    public LoadMoreListViewContainer mLoadMoreLayout;
    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        isguanzhu_x = getIntent().getStringExtra("istongshi");
        gzuid = getIntent().getStringExtra("isguanzhu_uid");

        initView();
        initRequestData();
        initRefresh();
        initLoadMore();
        initMenu();

    }
    /**
     * 初始化 加载更多
     */
    protected void initLoadMore() {
//        mLoadMoreLayout.setAutoLoadMore(true);
//        mLoadMoreLayout.setOffsetSize(3);
//        mLoadMoreLayout.useDefaultFooter();
//        mLoadMoreLayout.setLoadMoreHandler(this);
    }
    private void initRequestData() {
        mRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.autoRefresh(true);
            }
        }, 150);
        ivRightMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                menu_R.showMenu();
            }
        });
    }

    private void initRefresh() {
        mRefreshLayout.setLoadingMinTime(1000);
        mRefreshLayout.setPtrHandler(this);
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(mContext);
        mRefreshLayout.setHeaderView(header);
        mRefreshLayout.addPtrUIHandler(header);

    }

    private void initView() {
        backcowor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SaveTemporaryData.suoYouRen="";
                SaveTemporaryData.mSmart="";
                SaveTemporaryData.General = false;
                finish();
            }
        });

    }





    private void initData(String isfollow) {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "queryUnReadMessage");
        params.addBodyParameter("page", "1");
        params.addBodyParameter("pageSize","90000");
        Log.d("requestxx", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding() + "&serviceName=queryUnReadMessage" + "&page="+"1"+"&pageSize=100");
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                mRefreshLayout.refreshComplete();
                zanwushujufl.setVisibility(View.VISIBLE);
                Log.d("request获取系统消息Fail", arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Log.d("request获取系统成功", arg0.result.toString());
                Gson gson = new Gson();
                CnumberBean follow = gson.fromJson(arg0.result.toString(),
                        CnumberBean.class);
                guanzhudatea = follow.data;
                if (follow.data==null){
                    zanwushujufl.setVisibility(View.VISIBLE);
                    mRefreshLayout.refreshComplete();
                    return;
                }
                if (guanzhudatea.size() == 0) {
                    zanwushujufl.setVisibility(View.VISIBLE);
                } else {
                    zanwushujufl.setVisibility(View.INVISIBLE);
                }
                sortName = new NameComParatorMember();
                mRefreshLayout.clearAnimation();
//                mRefreshLayout.startAnimation();
                mRefreshLayout.refreshComplete();
                try {
//                    Collections.sort(guanzhudatea, sortName);
                    adapter = new NSystemAdapter(mContext, guanzhudatea, isguanzhu_x);
                    gzlist.setAdapter(adapter);
                } catch (Exception e) {
                }
            }
        });
    }

    public String createJson(String isfollow) {
        JSONObject object = new JSONObject();
        try {
            object.put("userId", gzuid);
            object.put("followType", isfollow);
            // Log.d("/////////////////", object.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return object.toString();

    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_draft_box_get_data;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, gzlist, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        if ("guanzhu".equals(isguanzhu_x)) {
            initData("mefollow");
        } else if ("beiguanzhu".equals(isguanzhu_x)) {
            initData("followme");
        } else {
            initData("mefollow");
        }

    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {

    }

    private class MyHeader extends MaterialHeader {

        public MyHeader(Context context) {
            super(context);
        }

        public MyHeader(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        public MyHeader(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        public void onUIRefreshComplete(PtrFrameLayout frame) {
            super.onUIRefreshComplete(frame);
        }

    }
    public SlidingMenu menu_R;
    private void initMenu() {
        Fragment leftMenuFragment = new MenuRightFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.id_Right_menu_frame, leftMenuFragment).commit();
        menu_R = new SlidingMenu(this);
        menu_R.setMode(SlidingMenu.RIGHT);
        menu_R.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); // 触摸边界拖出菜单
        menu_R.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu_R.setOffsetFadeDegree(0.4f);
        menu_R.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        View viewRi = LayoutInflater.from(this).inflate(R.layout.right_menu_id,
                null);
        menu_R.setMenu(viewRi);
    }
    /**
     * 监听Back键按下事件,方法1:
     * 注意:
     * super.onBackPressed()会自动调用finish()方法,关闭
     * 当前Activity.
     * 若要屏蔽Back键盘,注释该行代码即可
     */
    @Override
    public void onBackPressed() {
        SaveTemporaryData.suoYouRen="";
        SaveTemporaryData.mSmart="";
        SaveTemporaryData.General = true;
        super.onBackPressed();
    }
}
